<template>
  <div class="chat-container">
    <div class="messages" ref="messagesContainer">
      <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message', msg.role]"
      >
        <div class="bubble">
          <span v-if="msg.role === 'user'">你：</span>
          <span v-else>DeepSeek：</span>
          <br />
          <pre>{{ msg.content }}</pre>
        </div>
      </div>
    </div>

    <div class="input-area">
      <textarea
          v-model="input"
          placeholder="请输入你的问题..."
          :disabled="loading"
          rows="3"
      ></textarea>
      <button @click="sendPrompt" :disabled="loading || !input.trim()">发送</button>
    </div>

    <div v-if="loading" class="loading">生成中...</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      input: '',
      messages: [],
      loading: false,
      eventSource: null,
      currentAIResponse: '',
      bufferQueue: [],
      typingInterval: null,
    };
  },
  methods: {
    sendPrompt() {
      if (!this.input.trim()) return;

      const userMessage = { role: 'user', content: this.input.trim() };
      this.messages.push(userMessage);

      // 预留一个空位置给AI
      const aiMessage = { role: 'ai', content: '' };
      this.messages.push(aiMessage);

      this.loading = true;
      this.currentAIResponse = '';

      // 建立 EventSource 流
      this.eventSource = new EventSource(`http://localhost:2626/api/deepseek/stream?prompt=${encodeURIComponent(this.input)}`);

      this.input = '';

      let outputText = "";  // 存储正在显示的文本

      this.eventSource.onmessage = (event) => {
        if (event.data) {
          this.bufferQueue.push(event.data); // 先缓存这段文本
          this.startTyping(aiMessage);       // 触发统一的打字机逻辑
        }
      };

      this.eventSource.addEventListener('[END]', () => {
        this.loading = false;
        if (this.eventSource) {
          this.eventSource.close();
        }
        this.appendCharacterByCharacter(outputText, aiMessage);       // 触发统一的打字机逻辑
      });

      this.eventSource.onerror = (error) => {
        console.error('连接出错', error);
        this.loading = false;
        if (this.eventSource) {
          this.eventSource.close();
        }
      };
    },

    startTyping(aiMessage) {
      if (this.typingInterval) return; // 避免重复触发

      const speed = 50;
      this.typingInterval = setInterval(() => {
        if (this.bufferQueue.length === 0) {
          clearInterval(this.typingInterval);
          this.typingInterval = null;
          return;
        }

        const currentChunk = this.bufferQueue[0];
        if (!currentChunk || currentChunk.length === 0) {
          this.bufferQueue.shift();
          return;
        }

        const char = currentChunk[0];
        this.bufferQueue[0] = currentChunk.slice(1);
        aiMessage.content += char; // 正确拼接字符
        this.updateDisplay();
      }, speed);
    },

    updateDisplay() {
      // 在界面上更新当前显示的内容
      this.$nextTick(() => {
        // 手动触发 DOM 更新
        const container = this.$refs.messagesContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  }
};
</script>

<style scoped>
.chat-container {
  max-width: 700px;
  margin: 30px auto;
  display: flex;
  flex-direction: column;
  height: 80vh;
  border: 1px solid #ccc;
  border-radius: 10px;
  overflow: hidden;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  background-color: #f9f9f9;
}

.message {
  margin-bottom: 15px;
}

.message.user .bubble {
  background-color: #409EFF;
  color: white;
  text-align: left;
  padding: 10px;
  border-radius: 10px;
  max-width: 80%;
  margin-left: auto;
}

.message.ai .bubble {
  background-color: #e4e6eb;
  color: black;
  text-align: left;
  padding: 10px;
  border-radius: 10px;
  max-width: 80%;
  margin-right: auto;
}

.input-area {
  padding: 10px;
  display: flex;
  align-items: center;
  background: white;
}

textarea {
  flex: 1;
  resize: none;
  padding: 10px;
  margin-right: 10px;
}

button {
  background-color: #409EFF;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
  border-radius: 5px;
}

button:disabled {
  background: #aaa;
  cursor: not-allowed;
}

.loading {
  text-align: center;
  color: #409EFF;
  font-weight: bold;
  padding: 10px 0;
}
</style>

